from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from config import Config
from flask import request, make_response

# 1. 初始化扩展（先不绑定 Flask 应用，避免提前依赖）
db = SQLAlchemy()
ma = Marshmallow()

# 2. 【关键步骤】先导入所有模型（按依赖链排序，无依赖→被依赖→主模型）
# 基础无依赖模型
from app.auth.models import User
from app.categories.models import Category
from app.tags.models import Tag
from app.ingredients.models import Ingredient

# 主模型（依赖基础模型）
from app.recipes.models import Recipe, RecipeStep, RecipeIngredient, RecipeTag

# 依赖主模型的关联模型
from app.ingredients.models import Nutrition  # 依赖 Recipe
from app.comments.models import Comment      # 依赖 Recipe + User
from app.favorites.models import Favorite    # 依赖 Recipe + User
from app.likes.models import Like            # 依赖 Recipe + User

# 3. 应用工厂函数（创建并配置 Flask 应用）
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)  # 加载配置文件

    # 绑定扩展到 Flask 应用
    db.init_app(app)
    ma.init_app(app)
    # 配置CORS，处理所有跨域请求
    CORS(app, resources={r"/*": {
        "origins": ["http://localhost:5173", "http://127.0.0.1:5173"],
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["content-type", "Authorization", "X-Requested-With"],
        "supports_credentials": True,
        "send_wildcard": False,
        "always_send": True
    }})
    
    # 设置全局strict_slashes=False，必须在注册蓝图之前设置才能生效
    app.url_map.strict_slashes = False

    # 4. 创建数据库表（所有模型已导入，可安全执行）
    with app.app_context():
        db.create_all()

    # 5. 【最后步骤】加载并注册所有蓝图（此时模型/Schema 已全部就绪）
    # Auth 模块
    from app.auth.routes import auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    # Users 模块
    from app.users.routes import users_bp
    app.register_blueprint(users_bp, url_prefix='/users')

    # Categories 模块
    from app.categories.routes import categories_bp
    app.register_blueprint(categories_bp, url_prefix='/categories')

    # Tags 模块
    from app.tags.routes import tags_bp
    app.register_blueprint(tags_bp, url_prefix='/tags')

    # Recipes 模块
    from app.recipes.routes import recipes_bp
    app.register_blueprint(recipes_bp, url_prefix='/recipes')

    # Ingredients 模块
    from app.ingredients.routes import ingredients_bp
    app.register_blueprint(ingredients_bp, url_prefix='/ingredients')

    # Comments 模块
    from app.comments.routes import comments_bp
    app.register_blueprint(comments_bp, url_prefix='/comments')

    # Favorites 模块
    from app.favorites.routes import favorites_bp
    app.register_blueprint(favorites_bp, url_prefix='/favorites')

    # Likes 模块
    from app.likes.routes import likes_bp
    app.register_blueprint(likes_bp, url_prefix='/likes')

        # 移除自定义OPTIONS请求处理，让Flask-CORS自动处理
    # Flask-CORS会根据我们配置的resources自动处理所有CORS相关的请求头和响应

    # 全局strict_slashes=False已在蓝图注册前设置，这里不再重复设置

    return app